<template>
  <div class="schedule-management-container">
    <!-- 查询 -->
    <div class="search-container">
      <el-input
          placeholder="请输入员工姓名"
          style="width: 200px"
          v-model="searchQuery"
          class="search-input"
      ></el-input>
      <el-button
          @click="fetchSchedules"
          type="success"
          plain
          class="search-button"
      >
        查询
      </el-button>
      <el-button
          @click="openAddDialog"
          type="primary"
          class="register-button"
      >
        新增排班
      </el-button>
    </div>

    <!-- 错误信息 -->
    <div class="error-message" v-if="errorMessage">{{ errorMessage }}</div>

    <!-- 排班信息表格 -->
    <el-table
        :data="schedules"
        class="schedule-table"
        header-cell-class-name="table-header"
    >
      <el-table-column
          label="序号"
          type="index"
          width="60px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="id"
          label="排班 ID"
          width="100px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="employeeName"
          label="员工姓名"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="scheduleDate"
          label="排班日期"
          width="120px"
          align="center"
          :formatter="formatDate"
      ></el-table-column>
      <el-table-column
          prop="startTime"
          label="上班时间"
          width="120px"
          align="center"
          :formatter="formatTime"
      ></el-table-column>
      <el-table-column
          prop="endTime"
          label="下班时间"
          width="120px"
          align="center"
          :formatter="formatTime"
      ></el-table-column>
      <el-table-column label="操作" width="160px" align="center">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="openEditDialog(scope.row.id)"
              class="edit-button"
          >
            编辑
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="deleteSchedule(scope.row.id)"
              class="delete-button"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
      />
    </div>

    <!-- 排班信息对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        class="schedule-dialog"
    >
      <el-form :model="dialogForm" class="schedule-form">
        <el-form-item label="排班 ID" class="form-item" v-if="dialogOptType === 2">
          <el-col :span="11">
            <el-input v-model="dialogForm.id" disabled class="form-input"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="员工 ID" class="form-item">
          <el-col :span="11">
            <el-input v-model="dialogForm.employeeId" class="form-input"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="员工姓名" class="form-item" v-if="dialogForm.employeeName">
          <el-col :span="11">
            <el-tag>{{ dialogForm.employeeName }}</el-tag>
          </el-col>
        </el-form-item>
        <el-form-item label="排班日期" class="form-item">
          <el-col :span="11">
            <el-date-picker
                v-model="dialogForm.scheduleDate"
                type="date"
                placeholder="选择日期"
                class="form-input"
            ></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="上班时间" class="form-item">
          <el-col :span="11">
            <el-time-picker
                v-model="dialogForm.startTime"
                placeholder="选择时间"
                class="form-input"
            ></el-time-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="下班时间" class="form-item">
          <el-col :span="11">
            <el-time-picker
                v-model="dialogForm.endTime"
                placeholder="选择时间"
                class="form-input"
            ></el-time-picker>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="optOne()" class="dialog-button">{{ dialogButtonText }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import http from '@/axios/http';

// 存放排班数据集合
let schedules = ref([]);

// 报错提示
let errorMessage = ref("");

// 模糊查询绑定的 员工姓名
let searchQuery = ref("");

// 对话框显示控制
let dialogVisible = ref(false);

// 排班信息，或者编辑已有排班的 绑定数据
let dialogForm = ref({
  id: null,
  employeeId: '',
  employeeName: '',
  scheduleDate: null,
  startTime: null,
  endTime: null
});

// 新增、修改排班信息弹出框的 标题和操作按钮  显示文字
let dialogTitle = ref("");
let dialogButtonText = ref("");

// 对话框操作类型：1：添加 2：编辑
let dialogOptType = ref(1);

// 分页相关
let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);

// 根据员工姓名模糊查询排班信息
const fetchSchedules = async () => {
  try {
    const param = {
      employeeName: searchQuery.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    };
    const response = await http.post('/glsb/getAllSchedules', param);
    const result = response.data;
    if (result.result ==='success') {
      pageNum.value = result.data.pageNum;
      pageSize.value = result.data.pageSize;
      total.value = result.data.total;
      schedules.value = result.data.records;
      errorMessage.value = '';
    } else {
      errorMessage.value = result.error;
    }
  } catch (error) {
    errorMessage.value = `获取排班信息出错：${error.message}`;
  }
};

// 显示排班信息对话框
const openAddDialog = () => {
  dialogTitle.value = "新增排班";
  dialogButtonText.value = "新增";
  dialogVisible.value = true;
  dialogOptType.value = 1; // 设置当前操作类型标志是 新增
  dialogForm.value = {
    id: null,
    employeeId: '',
    employeeName: '',
    scheduleDate: null,
    startTime: null,
    endTime: null
  };
};

// 关闭排班信息对话框
const closeDialog = () => {
  dialogVisible.value = false;
  dialogForm.value = {
    id: null,
    employeeId: '',
    employeeName: '',
    scheduleDate: null,
    startTime: null,
    endTime: null
  };
};

// 页面初始化
onMounted(() => {
  fetchSchedules();
});

// 格式化日期字段
const formatDate = (row, column) => {
  if (!row ||!row.scheduleDate) {
    return '';
  }
  return new Date(row.scheduleDate).toLocaleDateString();
};

// 格式化时间字段
const formatTime = (row, column) => {
  if (!row ||!row[column.property]) {
    return '';
  }
  return new Date(row[column.property]).toLocaleTimeString();
};

// 新增排班信息
const addSchedule = async () => {
  try {
    const param = dialogForm.value;
    // 前端验证必填字段
    if (!param.employeeId ||!param.scheduleDate ||!param.startTime ||!param.endTime) {
      errorMessage.value = "员工 ID、排班日期、上班时间和下班时间不能为空";
      return;
    }
    const response = await http.post('/glsb/addSchedule', param);
    const result = response.data;
    if (result.result ==='success') {
      closeDialog();
      await fetchSchedules(); // 刷新页面
    } else {
      errorMessage.value = result.error;
    }
  } catch (error) {
    errorMessage.value = `新增排班信息出错：${error.message}`;
  }
};

// 显示编辑对话框
const openEditDialog = async (scheduleId) => {
  try {
    await getScheduleInfo(scheduleId);
    dialogVisible.value = true;
    dialogTitle.value = "编辑排班";
    dialogButtonText.value = "修改";
    dialogOptType.value = 2; // 设置当前操作类型标志是 修改
  } catch (error) {
    errorMessage.value = `获取排班信息出错：${error.message}`;
  }
};

const getScheduleInfo = async (scheduleId) => {
  try {
    const param = {
      id: scheduleId
    };
    const response = await http.post('/glsb/getScheduleById', param);
    const result = response.data;
    if (result.result ==='success') {
      dialogForm.value = result.data;
      dialogForm.value.scheduleDate = new Date(dialogForm.value.scheduleDate);
      dialogForm.value.startTime = new Date(dialogForm.value.startTime);
      dialogForm.value.endTime = new Date(dialogForm.value.endTime);
    } else {
      errorMessage.value = result.error;
    }
  } catch (error) {
    errorMessage.value = `获取排班信息出错：${error.message}`;
  }
};

// 删除排班
const deleteSchedule = async (scheduleId) => {
  if (window.confirm('确定要删除该排班信息吗？')) {
    try {
      const param = {
        id: scheduleId
      };
      const response = await http.post('/glsb/deleteSchedule', param);
      const result = response.data;
      if (result.result ==='success') {
        await fetchSchedules(); // 刷新页面
      } else {
        errorMessage.value = result.error;
      }
    } catch (error) {
      errorMessage.value = `删除排班信息出错：${error.message}`;
    }
  }
};

// 编辑排班信息
const editSchedule = async () => {
  try {
    const param = dialogForm.value;
    // 确保 dialogForm 包含 id 字段
    if (!param.id) {
      errorMessage.value = "缺少必要的 id 字段";
      return;
    }
    param.scheduleDate = param.scheduleDate? param.scheduleDate.toISOString() : null;
    param.startTime = param.startTime? param.startTime.toISOString() : null;
    param.endTime = param.endTime? param.endTime.toISOString() : null;
    const response = await http.post('/glsb/updateSchedule', param);
    const result = response.data;
    if (result.result ==='success') {
      closeDialog();
      await fetchSchedules(); // 刷新页面
    } else {
      errorMessage.value = result.error;
    }
  } catch (error) {
    errorMessage.value = `编辑排班信息出错：${error.message}`;
  }
};

// 操作按钮
const optOne = () => {
  if (dialogOptType.value === 1) {
    addSchedule();
  } else if (dialogOptType.value === 2) {
    editSchedule();
  }
};

// 分页处理
const handlePageChange = (newPage) => {
  pageNum.value = newPage;
  fetchSchedules();
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchSchedules();
};
</script>

<style scoped>
.schedule-management-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.search-button {
  margin-right: 20px;
}

.register-button {
  width: 100px;
  font-weight: bold;
  font-size: 16px;
}

.error-message {
  color: #f56c6c;
  margin-bottom: 20px;
  text-align: center;
}

.schedule-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-header {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #333;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination {
  width: 100%;
}

.schedule-dialog {
  width: 500px;
}

.schedule-form {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-button {
  width: 100%;
  padding: 10px;
}
</style>